//
//  YueKeViewController.m
//  jiyujiaProgram
//
//  Created by 中良 赵 on 15/12/3.
//  Copyright © 2015年 中良 赵. All rights reserved.
//

#import "YueKeViewController.h"
#import "YueKeTableViewCell.h"
#import "PlaceholderTextView.h"
#import "ClassNameViewController.h"
#import "STAlertView.h"
#import "ClassTimeViewController.h"
#import "Common.h"
#import <CoreLocation/CoreLocation.h>


@interface YueKeViewController ()<UIScrollViewDelegate,UITextViewDelegate>
{
    NSString *className;
    NSString *classPrice;
    NSString *classBeizhu;
    NSString *classDatetime;
    NSString *classMethod;
    
    PlaceholderTextView *tv;
    
    CLLocationManager *_locationManager;
    NSString *_lat;
    NSString *_lng;
}
@property (nonatomic, strong) STAlertView *stAlertView;

@end

@implementation YueKeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(postStringToUp:) name:@"postStringToUp" object:nil];
    classDatetime=@"";
    tv=[[PlaceholderTextView alloc]init];
    [tv setDelegate:(id<UITextViewDelegate> _Nullable)self];
    classBeizhu=@"";
}
- (void)viewWillAppear:(BOOL)animated
{
    [_locationManager startUpdatingLocation];
    UserInfoManager *userInfo = [UserInfoManager sharedUserInfoManager];
    [userInfo loadUserInfoFromSanbox];
//    self.userTextField.text = userInfo.user;
//    self.passwordTextField.text = userInfo.password;
}


- (void)creatLocationManager
{
    _locationManager = [[CLLocationManager alloc] init];
    _locationManager.delegate = self;
    _locationManager.desiredAccuracy=kCLLocationAccuracyBest;
    
    if ([CLLocationManager authorizationStatus]==kCLAuthorizationStatusNotDetermined){
        [_locationManager requestWhenInUseAuthorization];
    }
    
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8) {
        [_locationManager requestWhenInUseAuthorization];
    }
    
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 9) {
        _locationManager.allowsBackgroundLocationUpdates = NO;
    }
}


- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{
    for (CLLocation *userLocation in locations) {
        if (_lat.length <1 &&_lng.length < 1) {
            _lat = [NSString stringWithFormat:@"%f",userLocation.coordinate.latitude];
            _lng = [NSString stringWithFormat:@"%f",userLocation.coordinate.longitude];
        }else{
            UserInfoManager *userInfo = [UserInfoManager sharedUserInfoManager];
            userInfo.lat = _lat;
            userInfo.lng = _lng;
            [_locationManager stopUpdatingLocation];
        }
        NSLog(@"***CLLOCATION***%@***",userLocation);
    }
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)postStringToUp:(NSNotification *)text{
    NSLog(@"string====%@",text.userInfo[@"classname"]);
    NSLog(@"time===%@",text.userInfo[@"time"]);
    if ([text.userInfo[@"classname"] length]) {
        className=text.userInfo[@"classname"];
    }
    if ([text.userInfo[@"time"] length]) {
        classDatetime=text.userInfo[@"time"];
    }
    [_tableview reloadData];
//    NSLog(@"car===%@",(CarlistModel*)text.userInfo[@"car"]);
//    if (text.userInfo[@"string"]) {
//        string=text.userInfo[@"string"];
//    }
//    if (text.userInfo[@"car"]) {
//        _carModel=(CarlistModel*)text.userInfo[@"car"];
//    }
//    if (text.userInfo[@"address"]) {
//        serviceAddress=text.userInfo[@"address"];
//    }
//    [_mytableview reloadData];
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 5;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row==2) {
        return 120.f;
    }
    return 66.f;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    switch (indexPath.row) {
        case 0:
        {
            ClassNameViewController *vc=[[ClassNameViewController alloc]init];
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
        case 1:
        {
            self.stAlertView = [[STAlertView alloc] initWithTitle:@"请输入课程费用"
                                                          message:@""
                                                    textFieldHint:@"课程费用"
                                                   textFieldValue:nil
                                                cancelButtonTitle:@"取消"
                                                otherButtonTitles:@"确定"
                                
                                                cancelButtonBlock:^{
                                                    NSLog(@"Please, give me some feedback!");
                                                } otherButtonBlock:^(NSString * result){
                                                    NSLog(@" You have said %@, but I can't store it :( . If you want, you can send it to me at hello@nestor.cat or via twitter @NestorMalet!", result);
                                                    classPrice=result;
                                                    [_tableview reloadData];
                                                }];
            
        }
            break;
        case 2:
        {

        }
            break;
        case 3:
        {
            ClassTimeViewController *vc=[[ClassTimeViewController alloc]init];
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
        case 4:
        {
            UIActionSheet *a = [[UIActionSheet alloc] initWithTitle:@"上课方式"
                                                           delegate:(id<UIActionSheetDelegate>)self
                                                  cancelButtonTitle:@"取消"
                                             destructiveButtonTitle:nil
                                                  otherButtonTitles:@"老师上门",@"学生上门",@"双方协商",@"在线授课", nil];
            a.tag=1;
            a.actionSheetStyle = UIBarStyleBlackTranslucent;
            [a showInView:self.view];
        }
            break;
            
        default:
            break;
   }
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *CellIdentifier = @"Cell";
    
    YueKeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
//    if (!cell) {
//        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
//    }
    if (cell == nil) {
        cell=[[[NSBundle mainBundle] loadNibNamed:@"YueKeTableViewCell" owner:self options:nil] objectAtIndex:0];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    switch (indexPath.row) {
        case 0:
        {
            cell.lblClassTitle.text=@"课程名称";
            cell.lblClassText.text=className;
        }
            break;
        case 1:
        {
            cell.lblClassTitle.text=@"课程费用";
            if ([classPrice length]) {
                cell.lblClassText.text=[NSString stringWithFormat:@"%@元",classPrice];
            }else{
                cell.lblClassText.text=@"";
            }

        }
            break;
        case 2:
        {
            cell.lblClassTitle.text=@"课程备注";
            cell.lblClassText.text=@"(已便授课老师更了解你的情况)";
            cell.lblClassText.textColor=[UIColor lightGrayColor];
            [cell.lblClassText setFont:[UIFont fontWithName:SystemFont size:12.f]];
            cell.imgTap.hidden=YES;
            
            cell.lblClassText.textAlignment=NSTextAlignmentLeft;
            [tv setFrame:CGRectMake(cell.lblClassTitle.frame.origin.x, cell.lblClassTitle.frame.origin.y+CGRectGetHeight(cell.lblClassTitle.frame)+10, cell.contentView.frame.size.width-20, 40.f)];
            [cell.contentView addSubview:tv];
            tv.placeholder=@"请输入备注";
        }
            break;
        case 3:
        {
            cell.lblClassTitle.text=@"上课时间";
            cell.lblClassText.text=classDatetime;
        }
            break;
        case 4:
        {
            cell.lblClassTitle.text=@"上课方式";
            cell.lblClassText.text=classMethod;
        }
            break;
            
        default:
            break;
    }
    return cell;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    NSLog(@"tag:%ld",(long)actionSheet.tag);
    NSLog(@"index:%ld",(long)buttonIndex);
//    @"老师上门",@"学生上门",@"双方协商",@"在线授课"
    if (actionSheet.tag==1) {
        switch (buttonIndex) {
            case 0:
                classMethod=@"老师上门";
                break;
            case 1:
                classMethod=@"学生上门";
                break;
            case 2:
                classMethod=@"双方协商";
                break;
            case 3:
                classMethod=@"在线授课";
                break;
            default:
                break;
        }
        
        [_tableview reloadData];
//            
//        }
    }else{
        //        @"上门服务",@"到店服务",@"由车主决定",
//        if (buttonIndex == 0) {
//            //            serviceMethod=@"包工包料";
//
//        }
//        if (buttonIndex == 1){
//            serviceAddress=@"到店服务";
//        }
//        if (buttonIndex == 2){
//            serviceAddress=@"由车主决定";
//        }

    }
    
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    [self.view endEditing:YES];
}


- (IBAction)backAction:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}
- (IBAction)confirmAction:(id)sender {
    UserInfoManager *userInfo = [UserInfoManager sharedUserInfoManager];
    [userInfo loadUserInfoFromSanbox];
    if (userInfo.lat.length >0 &&userInfo.lng.length > 0) {

        if (classPrice.length == 0) {
            SHOW_ALERT(@"提示", @"请填写课程价格", @"好的", nil, nil);
        }else if (className.length==0){
            SHOW_ALERT(@"提示", @"请选择课程", @"好的", nil, nil);
        }else if (classDatetime.length == 0){
            SHOW_ALERT(@"提示", @"请选择上课时间", @"好的", nil, nil);
        }else if (classMethod.length == 0){
            SHOW_ALERT(@"提示", @"请选择上课方式", @"好的", nil, nil);
        }else{
            NSArray *_arr = [className componentsSeparatedByString:NSLocalizedString(@"/", nil)];
            NSMutableString *datestring=[[NSMutableString alloc]initWithString:[classDatetime substringToIndex:19]];
            [datestring replaceCharactersInRange:[datestring rangeOfString:@" "] withString:@"T"];
            NSLog(@"%@",datestring);
        NSDictionary *param = @{
                                @"promulgator_Id":userInfo.memberModel.member_Id,
                                @"t_member_Id":@"",
                                @"promulgator_mark":@"2",
                                @"course_name":[_arr objectAtIndex:_arr.count-1],
                                @"price":classPrice,
                                @"course_content":classBeizhu,
                                @"class_time":datestring,
                                @"have_class_way":classMethod,
                                @"lng":userInfo.lng,
                                @"lat":userInfo.lat,
                                @"status":@"1"
                                };
        
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:param options:NSJSONWritingPrettyPrinted error:nil];
        NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        [[HttpManager defaultManager] postRequestToUrl:RequestURL(IWANTHAVECLASS) params:@{@"data":jsonString} complete:^(BOOL successed, NSDictionary *result) {
            NSLog(@"%@",result);
            if (successed) {
                if ([[NSString stringWithFormat:@"%@",[result objectForKey:@"errCode"]]isEqualToString:@"200"]) {
                    [SVProgressHUD showSuccessWithStatus:@"提交成功!"];
                    [self.navigationController popViewControllerAnimated:YES];
                }else{
                    [SVProgressHUD showSuccessWithStatus:[result objectForKey:@"errMsg"]];
                }

            }
        }];
        }
    }else{
        SHOW_ALERT(@"提示", @"请等待定位，再登录", @"确定", nil, nil);
    }


    
}

- (BOOL)textViewShouldEndEditing:(UITextView *)textView{
    return YES;
}
- (void)textViewDidEndEditing:(UITextView *)textView{
    classBeizhu=textView.text;
}
@end
